<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item>
              <el-input
                v-model="listQuery.keyword"
                placeholder="请输会员名称"
                clearable
                @keyup.enter.native="search()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-select v-model="listQuery.approveState" placeholder="请选择审核状态">
                <el-option
                  v-for="(item, index) in approvalList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                  @input="inputChange"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-select v-model="listQuery.amountState" placeholder="请选择会费状态">
                <el-option
                  v-for="(item, index) in amountStateList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                  @input="inputChange"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-select v-model="listQuery.vipLevelId" placeholder="请选择会员等级">
                <el-option
                  v-for="(item, index) in vipLevelIdOptions"
                  :key="index"
                  :label="item.levelName"
                  :value="item.id"
                  @input="inputChange"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-date-picker
                v-model="pickerVal"
                type="daterange"
                start-placeholder="到期开始日期"
                end-placeholder="到期结束日期"
                value-format="timestamp"
                clearable
                :editable="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">
                {{ $t("common.search") }}</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >{{ $t("common.reset") }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <div class="JNPF-common-head">
          <div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              v-has="'btn_add'"
              @click="addOrUpdateHandle()"
              >新增</el-button
            >
            <el-button plain @click="addVipAmount()">新增会费</el-button>
            <el-button plain v-has="'btn_reminders'" @click="callAmount()">会费催缴</el-button>
            <el-button type="text" icon="el-icon-download" v-has="'btn_download'" @click="exportData()"
              >导出</el-button
            >
            <el-button type="text" icon="el-icon-upload2" v-has="'btn_upload'" @click="uploadForm"
              >导入</el-button
            >
          </div>
          <div class="JNPF-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JNPF-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
          </div>
        </div>
        <JNPF-table
          v-loading="listLoading"
          :data="list"
          @sort-change="sortChange"
          :span-method="arraySpanMethod"
        >
          <el-table-column prop="vipName" label="会员名称" show-overflow-tooltip align="left" />
          <el-table-column prop="flowState" label="审核状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.flowState == 1">待审核</el-tag>
              <el-tag type="success" v-else-if="scope.row.flowState == 2"
                >已通过</el-tag
              >
              <el-tag type="danger" v-else-if="scope.row.flowState == 3"
                >已驳回</el-tag
              >
              <el-tag type="info" v-else-if="scope.row.flowState == 4"
                >已撤回</el-tag
              >
              <el-tag type="info" v-else-if="scope.row.flowState == 5"
                >已终止</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="expireTime" label="会费状态" align="left">
            <template slot-scope="scope">
              <span>{{ !scope.row.expireTime ? '--' : payTime(scope.row.expireTime) >= 0 ? "已缴费" : "已欠费" + payTime(scope.row.expireTime) + "天" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="expireTime" label="到期时间" align="left">
            <template slot-scope="scope">
              <span>{{ jnpf.dateFormat(scope.row.expireTime, 'YYYY-MM-DD') || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="enabledMark" label="是否启用" align="left">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enabledMark"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1" :inactive-value="0"
                @change="switchChange($event, scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="vipLevelName" label="会员等级" align="left" />
          <el-table-column prop="legalPhoneNum" label="会员账号" align="left" />
          <el-table-column prop="approveUserName" label="审核人" align="left" />
          <el-table-column prop="approveTime" label="审核时间" align="left" :formatter="jnpf.tableDateFormat" />
          <el-table-column label="操作" fixed="right" width="150">
            <template slot-scope="scope">
              <el-button type="text" v-has="'btn_edit'" @click="addOrUpdateHandle(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                type="text"
                class="JNPF-table-delBtn"
                v-has="'btn_remove'"
                @click="handleDel(scope.row.id)"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                v-has="'btn_detail'"
                @click="addOrUpdateHandle(scope.row.id, scope.row.flowState, 'detail')"
                >查看</el-button
              >
            </template>
          </el-table-column>
        </JNPF-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <el-dialog
      title="会费催缴"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <div>
        <el-form ref="form" :model="callForm" label-width="120px">
          <el-form-item label="类型：">
            <el-radio-group v-model="callForm.type">
              <el-radio :label="1">到期前</el-radio>
              <el-radio :label="2">到期后</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="天数：">
            <el-input
              v-model="callForm.days"
              type="number"
              min="0"
              :controls="false"
              placeholder="会员期限"
              clearable
              :style="{ width: '80%' }"
            >
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="催缴方式：">
            <el-radio-group v-model="callForm.remindersMethod">
              <el-radio :label="1">系统消息</el-radio>
              <el-radio :label="2">邮件通知</el-radio>
              <el-radio :label="3">短信通知</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCallForm">确 定</el-button>
      </span>
    </el-dialog>
    <FlowBox v-if="flowVisible" ref="FlowBox" @close="colseFlow" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <ImportForm v-if="importFormVisible" ref="importForm" @refresh="reset()" />
  </div>
</template>

<script>
import request from "@/utils/request";
import {
  vipInfoList,
  delVipInfo,
  vipInfoState,
  vipInfoReminders,
  vipLevelList
} from "@/api/asso/vip/vipInfo";
import FlowBox from "@/views/workFlow/components/FlowBox";
import ExportBox from "./ExportBox";
import ImportForm from "./ImportForm";
import columnList from "./columnList";

export default {
  components: { FlowBox, ExportBox, ImportForm },
  data() {
    return {
      expandObj: {},
      columnOptions: [],
      mergeList: [],
      exportList: [],
      columnList,

      query: {},
      treeProps: {
        children: "children",
        label: "fullName",
        value: "id",
      },
      list: [],
      listLoading: true,
      importFormVisible: false,
      dialogVisible: false,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        keyword: '',
        approveState: '',
        amountState: '',
        vipLevelId: '',
        startTime: '',
        endTime: ''
      },
      flowVisible: false,
      exportBoxVisible: false,
      creatoruseridOptions: [
        { fullName: "选项一", id: "1" },
        { fullName: "选项二", id: "2" },
      ],
      creatoruseridProps: { label: "fullName", value: "id" },
      vipLevelIdOptions: [],
      pickerVal: [],
      approvalList: [
        {
          id: 1,
          name: "待审核",
        },
        {
          id: 2,
          name: "已通过",
        },
        {
          id: 3,
          name: "已驳回",
        },
        {
          id: 4,
          name: "已撤回",
        },
        {
          id: 5,
          name: "已终止",
        },
      ],
      amountStateList: [
        {
          id: 1,
          name: "已缴费",
        },
        {
          id: 2,
          name: "已欠费",
        }
      ],
      callForm: {
        type: 1,
        days: 30,
        remindersMethod: 1,
      },
    };
  },
  computed: {
    menuId() {
      return this.$route.meta.modelId || "";
    },
  },
  created() {
    this.getColumnList(), this.initData();
    this.getVipGrade();
  },
  methods: {
    getColumnList() {
      // 没有开启权限
      this.columnOptions = this.transformColumnList(this.columnList);
    },
    transformColumnList(columnList) {
      let list = [];
      for (let i = 0; i < columnList.length; i++) {
        const e = columnList[i];
        if (!e.prop.includes("-")) {
          list.push(e);
        } else {
          let prop = e.prop.split("-")[0];
          let label = e.label.split("-")[0];
          let vModel = e.prop.split("-")[1];
          let newItem = {
            align: "center",
            jnpfKey: "table",
            prop,
            label,
            children: [],
          };
          e.vModel = vModel;
          if (!this.expandObj.hasOwnProperty(`${prop}Expand`))
            this.$set(this.expandObj, `${prop}Expand`, false);
          if (!list.some((o) => o.prop === prop)) list.push(newItem);
          for (let i = 0; i < list.length; i++) {
            if (list[i].prop === prop) {
              list[i].children.push(e);
              break;
            }
          }
        }
      }
      this.getMergeList(list);
      this.getExportList(list);
      return list;
    },
    arraySpanMethod({ column }) {
      for (let i = 0; i < this.mergeList.length; i++) {
        if (column.property == this.mergeList[i].prop) {
          return [this.mergeList[i].rowspan, this.mergeList[i].colspan];
        }
      }
    },
    getMergeList(list) {
      let newList = JSON.parse(JSON.stringify(list));
      newList.forEach((item) => {
        if (item.children && item.children.length) {
          let child = {
            prop: item.prop + "-child-first",
          };
          item.children.unshift(child);
        }
      });
      newList.forEach((item) => {
        if (item.children && item.children.length > 0) {
          item.children.forEach((child, index) => {
            if (index == 0) {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 1,
                colspan: item.children.length,
              });
            } else {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 0,
                colspan: 0,
              });
            }
          });
        } else {
          this.mergeList.push({
            prop: item.prop,
            rowspan: 1,
            colspan: 1,
          });
        }
      });
    },
    getExportList(list) {
      let exportList = [];
      for (let i = 0; i < list.length; i++) {
        if (list[i].jnpfKey === "table") {
          for (let j = 0; j < list[i].children.length; j++) {
            exportList.push(list[i].children[j]);
          }
        } else {
          exportList.push(list[i]);
        }
      }
      this.exportList = exportList;
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    initData() {
      this.listLoading = true;
      let query = {
        ...this.listQuery,
        ...this.query,
        dataType: 0,
        menuId: this.menuId,
      };
      vipInfoList(query)
        .then((res) => {
          this.list = res.data.list;
          this.total = res.data.pagination.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning",
      }).then(() => {
        delVipInfo(id).then((res) => {
          this.$message({
            type: "success",
            message: res.msg,
            onClose: () => {
              this.initData();
            },
          });
        });
      });
    },
    addOrUpdateHandle(id, flowState, type) {
      let data = {
        id: id || "",
        enCode: "VipInfo",
        flowId: "366191492642898245",
        formType: 1,
        opType: flowState ? 0 : "-1",
        status: flowState,
        stateType: type
      };
      this.flowVisible = true;
      this.$nextTick(() => {
        this.$refs.FlowBox.init(data);
      });
    },

    exportData() {
      this.exportBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.exportList);
      });
    },
    download(data) {
      let query = {
        ...data,
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      request({
        url: `/api/example/T_vip_info/Actions/Export`,
        method: "post",
        data: query,
      }).then((res) => {
        if (!res.data.url) return;
        this.jnpf.downloadFile(res.data.url);
        this.$refs.ExportBox.visible = false;
        this.exportBoxVisible = false;
      });
    },
    search() {
      if (this.pickerVal && this.pickerVal.length) {
        this.listQuery.startTime = this.pickerVal[0];
        this.listQuery.endTime = this.pickerVal[1];
      } else {
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
      this.listQuery.currentPage = 1;
      this.listQuery.pageSize = 20;
      this.listQuery.sort = "desc";
      this.listQuery.sidx = "";
      this.initData();
    },
    colseFlow(isrRefresh) {
      this.flowVisible = false;
      if (isrRefresh) this.reset();
    },
    reset() {
      this.pickerVal = [];
      this.listQuery.approveState = "";
      this.listQuery.vipLevelId = "";
      this.listQuery.keyword = "";
      this.listQuery.amountState = ''
      this.search();
    },
    // 获取会员等级列表数据
    getVipGrade() {
      vipLevelList().then((res) => {
        if (res.code == 200) {
          this.vipLevelIdOptions = res.data.list;
        }
      });
    },
    // 导入
    uploadForm() {
      this.importFormVisible = true;
      this.$nextTick(() => {
        this.$refs.importForm.init();
      });
    },
    payTime(time) {
      let beginDate = new Date();
      let endDate = new Date(time);
      let day = (endDate - beginDate) / (1000 * 60 * 60 * 24);
      var x = day
      var y = String(x).indexOf(".") + 1;//获取小数点的位置
      if(y > 0) { // 有小数进一位
        if(day > 0){
          day = day + 1
        } else {
          day = day + (-1)
        }
      }
      return parseInt(day)
    },
    // 新增会费
    addVipAmount() {
      this.$router.push("/asso/vip/vipAmount?type=" + 'add');
    },
    switchChange(e, row) {
      let text = e == 1 ? "启用" : "停用";
      let data = {
        enabledMark: e == 1 ? 1 : 0,
        id: row.id
      };
      this.$confirm(`是否${text}？`, "提示", {
        type: "warning",
      }).then(() => {
        vipInfoState(row.id, data).then((res) => {
          this.$message({
            type: "success",
            message: res.msg,
            onClose: () => {
              this.initData();
            },
          });
        })
      }).catch(() => {
        this.initData()
      })
    },
    // 催缴会费
    callAmount() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    confirmCallForm() {
      if(this.callForm.days < 1 ){
        this.$message.error('输入错误,请重新输入')
        return
      }
      vipInfoReminders(this.callForm).then((res) => {
        this.handleClose()
        this.$message({
          type: "success",
          message: res.msg,
          onClose: () => {
            this.initData();
          },
        });
      });
    },
    inputChange(){
        this.$forceUpdate()
    },
  },
};
</script>
